package com.example.dao;

import com.example.controller.request.PeriodicalRequest;
import com.example.entity.Periodical;
import io.micrometer.common.util.StringUtils;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
import org.springframework.data.jpa.domain.Specification;

import java.util.ArrayList;
import java.util.List;

public class PeriodicalSpecification implements Specification<Periodical> {

    private PeriodicalRequest periodicalRequest;

    public PeriodicalSpecification(PeriodicalRequest periodicalRequest) {
        this.periodicalRequest = periodicalRequest;
    }

    @Override
    public Predicate toPredicate(Root<Periodical> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        List<Predicate> predicates = new ArrayList<>();
        // 根据periodical属性模糊匹配
        if (StringUtils.isNotEmpty(periodicalRequest.getPeriodical())) {
            predicates.add(cb.like(root.get("periodical"), "%" + periodicalRequest.getPeriodical() + "%"));
        }
        // 根据categories属性精确匹配
        if (StringUtils.isNotEmpty(periodicalRequest.getCategories())) {
            predicates.add(cb.equal(root.get("categories"), periodicalRequest.getCategories()));
        }
        // 其他属性可以类似添加
        // ...

        // 使用and方法将所有的Predicate组合起来
        return cb.and(predicates.toArray(new Predicate[predicates.size()]));
    }
}
